using System;
using System.Collections.Generic;
using System.Drawing;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using ERP_SaaS_WinForm.生产工单_报工_工序.Process;

namespace ERP_SaaS_WinForm.生产工单_报工_工序
{
    public partial class MaterialListForm : Form
    {
        private DataGridView dgvMaterials;
        private Label lblTitle;
        private Label lblTotal;
        private Button btnRefresh;
        private Button btnAddMaterial;
        private Button btnDeleteMaterial;
        private Button btnClose;
        private int productionOrdersId;
        private List<ProductionMaterial> materials;
        private bool isReadOnly = false;

        public MaterialListForm(int productionOrdersId)
        {
            this.productionOrdersId = productionOrdersId;
            this.isReadOnly = false;
            InitializeComponent();
            InitializeForm();
        }
        
        public MaterialListForm(int productionOrdersId, bool readOnly)
        {
            this.productionOrdersId = productionOrdersId;
            this.isReadOnly = readOnly;
            InitializeComponent();
            InitializeForm();
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();
            
            // 窗体设置
            this.Text = isReadOnly ? "物料清单查看" : "物料清单";
            this.Size = new Size(1000, 600);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            
            this.ResumeLayout(false);
        }

        private void InitializeForm()
        {
            // 标题
            lblTitle = new Label
            {
                Text = "物料清单",
                Font = new Font("微软雅黑", 16, FontStyle.Bold),
                ForeColor = Color.FromArgb(64, 64, 64),
                Location = new Point(20, 20),
                Size = new Size(200, 30),
                TextAlign = ContentAlignment.MiddleLeft
            };

            // 数据表格
            dgvMaterials = new DataGridView
            {
                Location = new Point(20, 70),
                Size = new Size(940, 420),
                AllowUserToAddRows = false,
                AllowUserToDeleteRows = false,
                ReadOnly = true,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect,
                MultiSelect = true,
                AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill,
                RowHeadersVisible = false,
                BackgroundColor = Color.White,
                BorderStyle = BorderStyle.None,
                GridColor = Color.LightGray
            };

            // 设置表格样式
            dgvMaterials.DefaultCellStyle.SelectionBackColor = Color.FromArgb(230, 240, 250);
            dgvMaterials.DefaultCellStyle.SelectionForeColor = Color.Black;
            dgvMaterials.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(240, 240, 240);
            dgvMaterials.ColumnHeadersDefaultCellStyle.Font = new Font("微软雅黑", 9, FontStyle.Bold);
            dgvMaterials.ColumnHeadersDefaultCellStyle.ForeColor = Color.FromArgb(64, 64, 64);
            dgvMaterials.ColumnHeadersHeight = 35;
            dgvMaterials.RowTemplate.Height = 30;

            // 添加列
            dgvMaterials.Columns.AddRange(new DataGridViewColumn[]
            {
                new DataGridViewTextBoxColumn { Name = "序号", HeaderText = "序号", Width = 60 },
                new DataGridViewTextBoxColumn { Name = "物料编号", HeaderText = "物料编号", Width = 120 },
                new DataGridViewTextBoxColumn { Name = "物料名称", HeaderText = "物料名称", Width = 150 },
                new DataGridViewTextBoxColumn { Name = "规格型号", HeaderText = "规格型号", Width = 120 },
                new DataGridViewTextBoxColumn { Name = "单位", HeaderText = "单位", Width = 80 },
                new DataGridViewTextBoxColumn { Name = "当前库存", HeaderText = "当前库存", Width = 100 },
                new DataGridViewTextBoxColumn { Name = "库存上限", HeaderText = "库存上限", Width = 100 },
                new DataGridViewTextBoxColumn { Name = "库存下限", HeaderText = "库存下限", Width = 100 },
                new DataGridViewTextBoxColumn { Name = "采购价格", HeaderText = "采购价格", Width = 100 },
                new DataGridViewTextBoxColumn { Name = "仓库编号", HeaderText = "仓库编号", Width = 120 },
                new DataGridViewTextBoxColumn { Name = "物料状态", HeaderText = "物料状态", Width = 100 }
            });

            // 总量标签
            lblTotal = new Label
            {
                Text = "物料总量: 0",
                Font = new Font("微软雅黑", 10, FontStyle.Bold),
                ForeColor = Color.FromArgb(64, 64, 64),
                Location = new Point(20, 510),
                Size = new Size(200, 25),
                TextAlign = ContentAlignment.MiddleLeft
            };

            // 刷新按钮
            btnRefresh = new Button
            {
                Text = "刷新",
                Location = new Point(570, 510),
                Size = new Size(80, 30),
                BackColor = Color.FromArgb(70, 130, 180),
                ForeColor = Color.White,
                Font = new Font("微软雅黑", 9),
                FlatStyle = FlatStyle.Flat
            };
            btnRefresh.FlatAppearance.BorderSize = 0;
            btnRefresh.Click += BtnRefresh_Click;

            // 添加物料按钮
            btnAddMaterial = new Button
            {
                Text = "添加物料",
                Location = new Point(650, 510),
                Size = new Size(80, 30),
                BackColor = Color.FromArgb(34, 139, 34),
                ForeColor = Color.White,
                Font = new Font("微软雅黑", 9),
                FlatStyle = FlatStyle.Flat,
                Visible = !isReadOnly
            };
            btnAddMaterial.FlatAppearance.BorderSize = 0;
            btnAddMaterial.Click += BtnAddMaterial_Click;

            // 删除物料按钮
            btnDeleteMaterial = new Button
            {
                Text = "删除物料",
                Location = new Point(750, 510),
                Size = new Size(80, 30),
                BackColor = Color.FromArgb(220, 53, 69),
                ForeColor = Color.White,
                Font = new Font("微软雅黑", 9),
                FlatStyle = FlatStyle.Flat,
                Visible = !isReadOnly
            };
            btnDeleteMaterial.FlatAppearance.BorderSize = 0;
            btnDeleteMaterial.Click += BtnDeleteMaterial_Click;

            // 关闭按钮
            btnClose = new Button
            {
                Text = "关闭",
                Location = new Point(850, 510),
                Size = new Size(80, 30),
                BackColor = Color.FromArgb(128, 128, 128),
                ForeColor = Color.White,
                Font = new Font("微软雅黑", 9),
                FlatStyle = FlatStyle.Flat
            };
            btnClose.FlatAppearance.BorderSize = 0;
            btnClose.Click += BtnClose_Click;

            // 添加控件
            this.Controls.AddRange(new Control[]
            {
                lblTitle,
                dgvMaterials,
                lblTotal,
                btnRefresh,
                btnAddMaterial,
                btnDeleteMaterial,
                btnClose
            });

            // 加载数据
            LoadMaterialsAsync();
        }

        private async void LoadMaterialsAsync()
        {
            try
            {
                Console.WriteLine($"开始加载物料清单，工单ID: {productionOrdersId}");
                
                using (var httpClient = new HttpClient())
                {
                    httpClient.Timeout = TimeSpan.FromSeconds(15);
                    var url = $"http://localhost:5257/api/ProductionMaterial/ShowProductionMaterialTableCommand?ProductionOrdersId={productionOrdersId}";
                    Console.WriteLine($"请求URL: {url}");
                    
                    var response = await httpClient.GetAsync(url);
                    Console.WriteLine($"响应状态码: {response.StatusCode}");
                    
                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"响应JSON: {json}");
                        
                        var apiResponse = JsonConvert.DeserializeObject<ProductionMaterialApiResponse>(json);
                        
                        if (apiResponse?.code == 200 && apiResponse.data != null)
                        {
                            materials = new List<ProductionMaterial>(apiResponse.data);
                            Console.WriteLine($"成功加载 {materials.Count} 条物料数据");
                            DisplayMaterials();
                        }
                        else
                        {
                            var errorMsg = apiResponse?.message ?? "未知错误";
                            Console.WriteLine($"API返回错误: {errorMsg}");
                            MessageBox.Show($"加载失败: {errorMsg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        var errorContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"HTTP错误: {response.StatusCode}, 内容: {errorContent}");
                        MessageBox.Show($"网络请求失败: {response.StatusCode}\n{errorContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载物料清单异常: {ex.Message}");
                Console.WriteLine($"异常堆栈: {ex.StackTrace}");
                MessageBox.Show($"加载物料清单时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void DisplayMaterials()
        {
            try
            {
                dgvMaterials.Rows.Clear();
                Console.WriteLine($"开始显示物料数据，总数: {materials?.Count ?? 0}");
                
                if (materials == null || materials.Count == 0)
                {
                    lblTotal.Text = "物料总量: 0";
                    Console.WriteLine("没有物料数据可显示");
                    return;
                }

                int totalQuantity = 0;
                for (int i = 0; i < materials.Count; i++)
                {
                    var material = materials[i];
                    if (material == null) continue;
                    
                    var rowIndex = dgvMaterials.Rows.Add();
                    
                    // 安全地设置单元格值，避免空引用异常
                    dgvMaterials.Rows[rowIndex].Cells["序号"].Value = i + 1;
                    dgvMaterials.Rows[rowIndex].Cells["物料编号"].Value = material.materialCode ?? "-";
                    dgvMaterials.Rows[rowIndex].Cells["物料名称"].Value = material.materialName ?? "-";
                    dgvMaterials.Rows[rowIndex].Cells["规格型号"].Value = material.specification ?? "-";
                    dgvMaterials.Rows[rowIndex].Cells["单位"].Value = material.unit ?? "-";
                    dgvMaterials.Rows[rowIndex].Cells["当前库存"].Value = material.currentInventory;
                    dgvMaterials.Rows[rowIndex].Cells["库存上限"].Value = material.inventorylimit;
                    dgvMaterials.Rows[rowIndex].Cells["库存下限"].Value = material.inventorylevel;
                    dgvMaterials.Rows[rowIndex].Cells["采购价格"].Value = material.purchasePrice.ToString("F2");
                    dgvMaterials.Rows[rowIndex].Cells["仓库编号"].Value = material.warehouseCode ?? "-";
                    dgvMaterials.Rows[rowIndex].Cells["物料状态"].Value = material.materialState ? "启用" : "禁用";

                    // 设置状态颜色
                    if (material.materialState)
                    {
                        dgvMaterials.Rows[rowIndex].Cells["物料状态"].Style.ForeColor = Color.FromArgb(34, 139, 34);
                    }
                    else
                    {
                        dgvMaterials.Rows[rowIndex].Cells["物料状态"].Style.ForeColor = Color.FromArgb(178, 34, 34);
                    }

                    totalQuantity += material.currentInventory;
                    
                    Console.WriteLine($"显示物料 {i + 1}: {material.materialName} (库存: {material.currentInventory})");
                }

                lblTotal.Text = $"物料总量: {totalQuantity}";
                Console.WriteLine($"物料显示完成，总库存: {totalQuantity}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"显示物料数据时发生错误: {ex.Message}");
                MessageBox.Show($"显示物料数据时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnRefresh_Click(object sender, EventArgs e)
        {
            LoadMaterialsAsync();
        }

        private void BtnAddMaterial_Click(object sender, EventArgs e)
        {
            try
            {
                var editForm = new MaterialEditForm(productionOrdersId);
                if (editForm.ShowDialog(this) == DialogResult.OK)
                {
                    // 添加成功后刷新列表
                    LoadMaterialsAsync();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开添加物料窗体时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnDeleteMaterial_Click(object sender, EventArgs e)
        {
            try
            {
                var selectedRows = dgvMaterials.SelectedRows;
                if (selectedRows.Count == 0)
                {
                    MessageBox.Show("请先选择要删除的物料", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                var result = MessageBox.Show($"确定要删除选中的 {selectedRows.Count} 个物料吗？", "确认删除", 
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                
                if (result == DialogResult.Yes)
                {
                    DeleteSelectedMaterials(selectedRows);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除物料时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void DeleteSelectedMaterials(DataGridViewSelectedRowCollection selectedRows)
        {
            try
            {
                var materialCodes = new List<string>();
                foreach (DataGridViewRow row in selectedRows)
                {
                    var materialCode = row.Cells["物料编号"].Value?.ToString();
                    if (!string.IsNullOrEmpty(materialCode))
                    {
                        materialCodes.Add(materialCode);
                    }
                }

                if (materialCodes.Count == 0)
                {
                    MessageBox.Show("没有找到有效的物料编号", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                var success = await DeleteMaterialsAsync(materialCodes);
                if (success)
                {
                    MessageBox.Show($"成功删除 {materialCodes.Count} 个物料", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    // 删除成功后刷新列表
                    LoadMaterialsAsync();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除物料时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async Task<bool> DeleteMaterialsAsync(List<string> materialCodes)
        {
            using (var httpClient = new HttpClient())
            {
                var request = new DelProductionMaterialCommand
                {
                    productionOrdersId = this.productionOrdersId,
                    materialCodes = materialCodes.ToArray()
                };

                var json = JsonConvert.SerializeObject(request);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var url = "http://localhost:5257/api/ProductionMaterial/DelProductionMaterialCommand";
                var response = await httpClient.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    var responseJson = await response.Content.ReadAsStringAsync();
                    var apiResponse = JsonConvert.DeserializeObject<DelProductionMaterialApiResponse>(responseJson);

                    if (apiResponse.code == 200)
                    {
                        return apiResponse.data;
                    }
                    else
                    {
                        throw new Exception(apiResponse.message ?? "删除失败");
                    }
                }
                else
                {
                    throw new Exception($"网络请求失败: {response.StatusCode}");
                }
            }
        }

        private void BtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
